using Autofac;
using CommonHelper.AutofacCommon;
using Microsoft.AspNetCore.Http;
using NLogInfo;
using System.Reflection;

namespace Order.MicroService.Api.Config
{
    public class AutofacModuleRegister : Autofac.Module
    {
        //重写Autofac管道Load方法，在这里注册注入
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
            builder.RegisterType<NLogHelper>().As<INLogHelper>().SingleInstance();

            //服务项目程序集
            Assembly service = Assembly.Load("Order.MicroService.Service");

            //服务接口项目程序集
            Assembly iservice = Assembly.Load("Order.MicroService.IService");

            builder.RegisterAssemblyTypes(service,iservice)
                .Where(n => n.FullName.EndsWith("Service") && !n.IsAbstract)  //筛选条件                                                                         
                .AsImplementedInterfaces()  //接口注入
                .InstancePerLifetimeScope();        //生命周期：单例模式
                //.PropertiesAutowired(new AutowiredPropertySelector()); // 属性注入
                //.Except<OrderService>()  //排除哪些类


            //仓储类接口项目程序集
            Assembly repository = Assembly.Load("Order.MicroService.Repository");

            Assembly irepository = Assembly.Load("Order.MicroService.IRepository");

            builder.RegisterAssemblyTypes(repository, irepository)
                .Where(n => n.FullName.EndsWith("Repository") && !n.IsAbstract)  //筛选条件
                                                                                 //.Except<OrderService>()  //排除哪些类
                .AsImplementedInterfaces()  //接口注入
                .InstancePerLifetimeScope();         //生命周期：单例模式


            //builder.RegisterType<OrderService>().As<IOrderService>().InstancePerDependency().AsImplementedInterfaces();
            //builder.RegisterType<TestService>().As<ITestService>().InstancePerDependency().AsImplementedInterfaces();


            //var controllerBaseType = typeof(ControllerBase);
            //builder.RegisterAssemblyTypes(typeof(Program).Assembly)
            //    .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
            //    .PropertiesAutowired(new AutowiredPropertySelector());

            //var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
            // .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
            //builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(new AutowiredPropertySelector());


            //builder.RegisterType<TestService>().As<ITestService>().SingleInstance()
            //    .PropertiesAutowired(new AutowiredPropertySelector());

            //builder.RegisterType<OrderService>().As<IOrderService>().SingleInstance();
        }
    }
}
